using DG.Tweening;
using UnityEngine;
using UnityEngine.UI;
using UnityGameFramework.Runtime;

namespace StarForce.Hotfix
{
    public class Tip : HotfixEntity
    {
        private TipData m_TipData;

        private Text m_TipText;

        private float m_HiddenTime;

        private float m_HiddenTiming;

        private Tweener m_Tiptweener;

        private bool m_active;

        public override void OnInit(StarForce.HotfixEntity entityLogic, object userData)
        {
            base.OnInit(entityLogic, userData);
            m_TipText = entityLogic.transform.GetChild(0).GetComponent<Text>();
            
            m_HiddenTime = 1.5f;

            m_HiddenTiming = 0;
        }

        public override void OnShow(object userData)
        {
            base.OnShow(userData);
            
            m_TipData = (TipData) userData;
            m_active = true;
            m_HiddenTime = 1.5f;
            EntityLogic.transform.GetComponent<CanvasGroup>().alpha = 1;
            m_TipText.text = m_TipData.TipTxt;
            
            EntityLogic.transform.localPosition = Vector3.zero;
            EntityLogic.transform.localScale = Vector3.zero;
            EntityLogic.transform.DOScale(new Vector3(1.1f, 1.1f, 1.1f), 0.3f).SetEase(Ease.Linear).OnComplete(() =>
            {
                EntityLogic.transform.DOScale(Vector3.one,0.2f).SetEase(Ease.InOutBounce);
            });
        }

        public override void OnUpdate(float elapseSeconds, float realElapseSeconds)
        {
            base.OnUpdate(elapseSeconds, realElapseSeconds);
            if (m_HiddenTiming < m_HiddenTime)
            {
                m_HiddenTiming += realElapseSeconds;
            }
            else
            {
                m_HiddenTiming = 0;
                if (m_active)
                {
                    EntityLogic.transform.GetComponent<CanvasGroup>().alpha = 1;
                    EntityLogic.transform.DOLocalMoveY(1000, 10f).SetEase(Ease.Linear);
                    m_Tiptweener = DOTween.To(() => EntityLogic.transform.GetComponent<CanvasGroup>().alpha, x => EntityLogic.transform.GetComponent<CanvasGroup>().alpha = x,  0 , 2f).OnComplete(() =>
                    {
                        if (GameEntry.Entity.HasEntity(EntityLogic.Entity.Id))
                        {
                            EntityLogic.transform.DOKill();
                            GameEntry.Entity.HideEntity(EntityLogic.Entity);
                        }
                    });
                }

                m_active = false;
            }
        }

        public override void OnHide(bool isShutdown, object userData)
        {
            base.OnHide(isShutdown, userData);

            m_active = true;
            EntityLogic.transform.DOKill();
            m_Tiptweener.Kill();
            EntityLogic.transform.GetComponent<CanvasGroup>().alpha = 1;
            EntityLogic.transform.localPosition = Vector3.zero;
        }
    }
}